package com.gzz.controller;


import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gzz.common.R;
import com.gzz.pojo.ImgsResp;
import com.gzz.pojo.Strategy;
import com.gzz.pojo.SystemMessage;
import com.gzz.pojo.User;
import com.gzz.service.*;
import com.gzz.utils.AliContextCheck;
import com.gzz.utils.JWTUtils;
import com.gzz.utils.OssUtils;
import com.gzz.vo.SenceryDetailVo;
import com.gzz.vo.StrategyDetailVo;
import com.gzz.vo.StrategyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.gzz.utils.OssUtils.StrategyTypeId;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 */
@RestController
@RequestMapping("/api/strategy")
public class StrategyController {

	@Autowired
	OssUploadService ossUploadService;
	//上传服务对象
	@Autowired
	ImgsRespService imgsRespService;
	//图片路径记录对象
	@Autowired
	UserService userService;
	//用户服务对象
	@Autowired
	StrategyService strategyService;
	//攻略服务对象
	@Autowired
	SystemMessageService systemMessageService;
	//系统信息拂去对象
	@Autowired
	RedisService redisService;
	//Redis缓存服务对象
	@GetMapping("/list")//攻略搜索接口
	public R<Page> getlist(String keyword, int pageNo, int pageSize){
		return strategyService.getListByTitle(keyword,pageNo,pageSize);
	}

	@GetMapping("/adminlist")
	R<PageInfo<StrategyDetailVo>> getDetailAll(HttpServletRequest request, int pageNum, int pageSize, String search, Long userId,Integer s_status,Integer s_isPublic){
		PageHelper.startPage(pageNum,pageSize);
		R<List<StrategyDetailVo>> r = strategyService.getDetailAll(search,userId,s_status,s_isPublic);
		List<StrategyDetailVo> list = r.getData();

		PageInfo<StrategyDetailVo> pageInfo = new PageInfo<>(list);
		pageInfo.setTotal(strategyService.getTotalbyCondition(search,userId,s_status,s_isPublic));
		return R.success(pageInfo);
	}
	@GetMapping("/check")
	public R<String> check(Long userId, Long stId,Integer status){

		LambdaUpdateWrapper<Strategy> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(Strategy::getStId,stId).set(Strategy::getStatus,status);
		strategyService.update(updateWrapper);
		SystemMessage systemMessage = new SystemMessage();
		Long msgId = (long) Math.abs(UUID.randomUUID().hashCode());
		systemMessage.setId(msgId);
		if(status==1){
			systemMessage.setContext("你发布的一条攻略已审核通过");
		}else{
			systemMessage.setContext("你发布的一条攻略已审核未通过");
		}
		systemMessage.setTitle("系统信息");
		systemMessage.setUserId(userId);
		systemMessage.setCreateTime(new Date());
		systemMessageService.save(systemMessage);
		return R.success("成功");
	}

	@GetMapping("/updatePub")
	public R<String> check(Long stId,boolean pub){
		LambdaUpdateWrapper<Strategy> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(Strategy::getStId,stId).set(Strategy::getPub,pub);
		strategyService.update(updateWrapper);
		return R.success("成功");
	}

	@PostMapping("/adminadd")
	public R<String> adminadd(HttpServletRequest request,@RequestBody StrategyDetailVo strategyDetailVo){
		String token = request.getHeader("token");
		//获取用户id
		Long id = JWTUtils.parseToken(token);
		Long stId = (long)Math.abs(UUID.randomUUID().hashCode());

		Strategy strategy = new Strategy();
		BeanUtils.copyProperties(strategyDetailVo,strategy);
		strategy.setUpdateTime(new Date());
		strategy.setCreateTime(new Date());
		strategy.setUserId(id);
		//管理员上传默认是审核成功
		strategy.setPub(true);
		strategy.setStatus(1);

		strategyService.save(strategy);

		List<String> imgs = strategyDetailVo.getDetailImgs();

		Integer typeId = StrategyTypeId;
		boolean r = imgsRespService.saveList(imgs,stId,typeId);
		if(!r){
			return R.error("数据异常");
		}
		return  R.success("成功分享攻略");


	}


	@GetMapping("/detail")
	public R<StrategyDetailVo> getStrategyDetail(HttpServletRequest request, Long stId){
		String token = request.getHeader("token");
		//获取用户id
		Long id = JWTUtils.parseToken(token);

		R<StrategyDetailVo> strategyDetail = strategyService.getStrategyDetail(stId);
		StrategyDetailVo strategyDetailVo = strategyDetail.getData();
		Integer status = redisService.getLikeStatus(stId,id);

		if(status!=null){
			 if(status==1){
				 strategyDetailVo.setStZan(strategyDetailVo.getStZan()+1);
			 }else{
				 strategyDetailVo.setStZan(strategyDetailVo.getStZan()-1);
			 }
		}

		return R.success(strategyDetailVo);


	}
	@PostMapping("/upload")
	public R<String> UploadImg(String type,@RequestParam("file") MultipartFile multipartFile){
		String imgUrl = ossUploadService.uploadFile(multipartFile,type);
		if(imgUrl!="error"){
			return R.success(imgUrl);
		}
		return R.error(imgUrl);
	}
	@GetMapping("/del")
	public R<String>delbystId(HttpServletRequest request,HttpServletResponse response,Long stId){
		String token = request.getHeader("token");
		//获取用户id
		Long id = JWTUtils.parseToken(token);
		User user = userService.getById(id);

		if(user==null){
			response.setStatus(401);
			return R.error("请登录");
		}

		boolean row = strategyService.removeById(stId);

		boolean f = imgsRespService.removeByIdAndTypeId(stId,StrategyTypeId);
		if(f&&row){
			return R.success("成功");
		}
		else{
			return R.error("删除失败");
		}
	}

	@GetMapping("/myList")
	public R<List<Strategy>> getMyAll(HttpServletRequest request,HttpServletResponse response){
		String token = request.getHeader("token");
		//获取用户id
		Long id = JWTUtils.parseToken(token);
		User user = userService.getById(id);

		if(user==null){
			response.setStatus(401);
			return R.error("请登录");
		}


		List<Strategy> list = strategyService.getListByUserId(id);
		List<Strategy> reslist = new ArrayList<>();
		list.forEach(item->{
			if(item.getPub()&&item.getStatus()==1){
				reslist.add(item);
			}
		});

		if(reslist==null){
			return R.error("暂无数据");
		}
		return  R.success(reslist);
	}

	@PostMapping("/add")
	public R<String> AddSt(HttpServletRequest request, HttpServletResponse response, @RequestBody StrategyVo article) throws Exception {
		String token = request.getHeader("token");
		//获取用户id
		Long id = JWTUtils.parseToken(token);
		User user = userService.getById(id);
		if(user==null){
			response.setStatus(401);
			return R.error("请登录");
		}
		Long stId = (long) Math.abs(UUID.randomUUID().hashCode());

		//存入攻略表
		String title = article.getStTitle();
		String context = article.getContext();
		String coverImage = article.getStCoverImage();
		Strategy strategy = new Strategy();
		strategy.setUserId(id);
		strategy.setContext(context);
		strategy.setCreateTime(new Date());
		strategy.setUpdateTime(new Date());
		strategy.setStCoverImage(coverImage);
		strategy.setStId(stId);
		strategy.setStTitle(title);
		strategy.setPub(true);
		boolean c = false;
		try {
			c = AliContextCheck.checkText(context);
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean d = true;
		d = AliContextCheck.checkImag(coverImage);


		//存入图片仓库

		List<String> imgs = article.getDetailImgs();
		for(int i=0;i<imgs.size();i++){
			if(!AliContextCheck.checkImag(imgs.get(i))){
				d = false;
				break;
			}
		}
		if(d&&c){
			strategy.setStatus(1);
		}
		boolean row = strategyService.save(strategy);

		if(!row){
			return R.error("数据异常");
		}

		Integer typeId = StrategyTypeId;



		boolean r = imgsRespService.saveList(imgs,stId,typeId);
		if(!r){
			return R.error("数据异常");
		}
		if(d&&c){
			SystemMessage systemMessage = new SystemMessage();
			Long msgId = (long) Math.abs(UUID.randomUUID().hashCode());
			systemMessage.setId(msgId);
			systemMessage.setContext("你发布的一条攻略已审核通过");
			systemMessage.setTitle("系统信息");
			systemMessage.setUserId(id);
			systemMessage.setCreateTime(new Date());
			systemMessageService.save(systemMessage);
		}
		return  R.success("成功分享攻略");
	}


}

